import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Http } from '@angular/http';
import { LeftSidebarService } from '../sidebar/left-sidebar-service';
import { BaseComponet } from '../BaseComponet';
import { Subscription } from 'rxjs';

declare var $: any;
@Component({
    selector: 'app-org-management',
    templateUrl: './org-management.component.html',
    styleUrls: ['./org-management.component.css']
})
export class OrgManagementComponent extends BaseComponet
    implements OnInit, OnDestroy {
    public isOnShow = true;
    public orgId: String;
    public orgName: String;
    public subLinks: any[];
    public pageNo: number;
    public pageSize: number;
    public orderBy: String;
    public orderType: String;
    public searchKeywords: String;
    public total: number;
    public orgs: any[];
    public totalPages: number;
    public parentId: String;
    public displayUpBottonStyle: String;
    public toAddOrgName: String;
    public toAddIsLocked: boolean;
    public toAddOrgCode: String;
    public toAddOrgType: String;
    public checkedOrgIds: any[];
    public checkedAll: boolean;
    public toModifyOrgId: String;
    public toModifyOrgName: String;
    public toModifyOrgCode: String;
    public toModifyOrgType: String;
    public toModifyIsLocked: boolean;
    public toMoveOrgTree: any;
    public moveToOrgId: String;
    public menus: any[];
    public showAdd = false;
    public showModify = false;
    public showMoveTo = false;
    public showDelete = false;
    public showLock = false;
    public showUnlock = false;
    public displayOrgTree: any;
    public minPageNo: number;
    public minPageSize: number;
    public minOrderBy: String = '';
    public minOrderType: String = '';
    public minSearchKeywords: String = '';
    public minTotal: number;
    public minTotalPages: number;
    public minPageOrgId: String;
    public userJobRolesOrgName: String;
    public jobUserRoles: any[];
    public checkedUserJobRoleIds: any[];
    public checkedAllUserJobRoles: boolean;
    public showUserJobRoles = false;
    public showDeleteUserJobRoles = false;
    public menuChangeSubscription: Subscription;
    constructor(
        public routerInfo: ActivatedRoute,
        public http: Http,
        public router: Router,
        public leftSidebarService: LeftSidebarService
    ) {
        super();
    }
    switchButtons() {
        this.menus = JSON.parse(sessionStorage.getItem('menus'));
        if (this.menus.indexOf('manager:org.back.add') > -1) {
            this.showAdd = true;
        } else {
            this.showAdd = false;
        }
        if (this.menus.indexOf('manager:org.back.modify') > -1) {
            this.showModify = true;
        } else {
            this.showModify = false;
        }
        if (this.menus.indexOf('manager:org.back.move-to') > -1) {
            this.showMoveTo = true;
        } else {
            this.showMoveTo = false;
        }
        if (this.menus.indexOf('manager:org.back.delete-by-ids') > -1) {
            this.showDelete = true;
        } else {
            this.showDelete = false;
        }
        if (this.menus.indexOf('manager:org.back.lock') > -1) {
            this.showLock = true;
        } else {
            this.showLock = false;
        }
        if (this.menus.indexOf('manager:org.back.unlock') > -1) {
            this.showUnlock = true;
        } else {
            this.showUnlock = false;
        }
        if (
            this.menus.indexOf('manager:job.back.manage-org-jobs-roles.query') >
            -1
        ) {
            this.showUserJobRoles = true;
        } else {
            this.showUserJobRoles = false;
        }
        if (
            this.menus.indexOf('manager:job.back.manage-role-jobs.delete') > -1
        ) {
            this.showDeleteUserJobRoles = true;
        } else {
            this.showDeleteUserJobRoles = false;
        }
    }
    ngOnDestroy() {
        this.isOnShow = false;
        console.log('ngOnDestroy()');
        $('.popover').remove();
        this.menuChangeSubscription.unsubscribe();
    }
    ngOnInit() {
        this.isOnShow = true;
        this.toMoveOrgTree = {};
        this.displayOrgTree = {};
        $('[data-toggle="popover"]').popover();
        this.switchButtons();
        this.menuChangeSubscription = this.leftSidebarService.menusChange.subscribe(
            command => {
                this.switchButtons();
            }
        );
        // $(document).on('show.bs.modal', '.modal', function () {
        //   $(this).draggable();
        //   $(this).css('overflow-y', 'scroll');
        //   // 防止出现滚动条，出现的话，你会把滚动条一起拖着走的
        // });
        // $('[data-toggle="popover"]').popover();
        this.routerInfo.params.subscribe((params: Params) => {
            this.orgId = params['orgId'];
            this.pageNo = params['pageNo'];
            this.pageSize = params['pageSize'];
            this.orderBy = params['orderBy'];
            this.orderType = params['orderType'];
            this.searchKeywords = params['searchKeywords'];
            if (this.orgId == null) {
                this.orgId = '';
            }
            if (this.orderBy == null) {
                this.orderBy = '';
            }
            if (this.orderType == null) {
                this.orderType = '';
            }
            if (this.searchKeywords == null) {
                this.searchKeywords = '';
            }
            if (this.pageNo == null) {
                this.pageNo = 1;
            } else {
                this.pageNo = parseInt(params['pageNo'], 10);
            }
            if (this.pageSize == null) {
                this.pageSize = parseInt(localStorage.getItem('pageSize'), 10);
                if (this.pageSize == null || isNaN(this.pageSize)) {
                    this.pageSize = 30;
                }
            } else {
                localStorage.setItem('pageSize', '' + this.pageSize);
            }
            this.displayData();
        });
    }
    displayData() {
        this.checkedOrgIds = [];
        this.checkedAll = false;
        this.showLoading();
        if (this.orgId == null || this.orgId === '' || this.orgId === '-1') {
            this.orgId = '-1';
            this.parentId = null;
            this.displayUpBottonStyle = 'none';
            this.orgName = '所有组织机构';
            this.subLinks = [];
            this.subLinks[0] = {
                orgId: '',
                orgName: '所有组织机构'
            };
            this.http
                .get(
                    '/user/back/org/page/parent-id--1/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        if (this.isOnShow) {
                            this.hideLoading();
                        }
                        this.total = result.total;
                        this.orgs = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {}
                );
        } else {
            this.http
                .get('/user/back/org/path/' + this.orgId)
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.displayUpBottonStyle = '';
                        this.orgName = result.orgName;
                        this.subLinks = result.orgPath;
                        if (this.subLinks.length > 1) {
                            this.parentId = this.subLinks[
                                this.subLinks.length - 2
                            ].orgId;
                        } else if (this.subLinks.length > 0) {
                            this.parentId = '-1';
                        } else {
                            this.parentId = null;
                        }
                        this.subLinks.unshift({
                            orgId: '',
                            orgName: '所有组织机构'
                        });
                    },
                    error => {
                        this.router.navigate(['org-management']);
                    }
                );
            this.http
                .get(
                    '/user/back/org/page/parent-id-' +
                        this.orgId +
                        '/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.hideLoading();
                        this.total = result.total;
                        this.orgs = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {
                        // this.router.navigate(['org-management']);
                    }
                );
        }
    }
    upToParent(parentId) {
        if (parentId == null) {
            alert('已经到达最上级');
            return;
        }
        this.orgId = parentId;
        this.pageNo = 1;
        this.router.navigate([
            'org-management/' +
                this.orgId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    sort(orderBy) {
        if (this.orderBy === orderBy) {
            if (this.orderType === 'asc') {
                this.orderType = 'desc';
            } else {
                this.orderType = 'asc';
            }
        } else {
            this.orderBy = orderBy;
        }
        this.router.navigate([
            'org-management/' +
                this.orgId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    clearKeywords() {
        this.searchKeywords = '';
    }
    setPageSize(pageSize) {
        this.pageSize = pageSize;
        this.pageNo = 1;
        localStorage.setItem('pageSize', '' + this.pageSize);
        this.router.navigate([
            'org-management/' +
                this.orgId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    goToPage(pageNo) {
        this.pageNo = pageNo;
        this.router.navigate([
            'org-management/' +
                this.orgId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    toAdd() {
        if (this.orgId != null && this.orgId !== '-1') {
            this.toAddIsLocked = false;
            this.toAddOrgName = '';
            this.toAddOrgCode = '';
            $('#addModal').modal('show');
        } else {
            alert('只能在自己所拥有的组织机构下增加新组织机构！');
        }
    }
    add() {
        this.http
            .post('/user/back/org/', {
                orgName: this.toAddOrgName,
                orgCode: this.toAddOrgCode,
                orgType: this.toAddOrgType,
                isLocked: this.toAddIsLocked,
                parentId: this.orgId
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#addModal').modal('hide');
                    this.goToPage(1);
                    this.displayData();
                    this.leftSidebarService.refresh.emit('orgManagement');
                },
                error => {}
            );
    }
    checkAll() {
        if (this.checkedAll === false) {
            this.checkedAll = true;
            this.checkedOrgIds = [];
            for (let i = 0; i < this.orgs.length; i++) {
                this.checkedOrgIds.push(this.orgs[i].orgId);
            }
            $('.org-list').prop('checked', true);
        } else {
            this.checkedAll = false;
            this.checkedOrgIds = [];
            $('.org-list').prop('checked', false);
        }
    }
    check(orgId) {
        this.checkedOrgIds = [];
        if ($('.org-list').length === $('.org-list:checked').length) {
            this.checkedAll = true;
        } else {
            this.checkedAll = false;
        }
        const checkedorgIds = this.checkedOrgIds;
        $('.org-list:checked').each(function() {
            checkedorgIds.push($(this).val());
        });
    }
    toDelete() {
        if (this.checkedOrgIds.length <= 0) {
            alert('请先选中需要删除的组织机构！');
            return;
        }
        if (confirm('确定删除选中的组织机构吗？')) {
            this.http
                .delete('/user/back/org/by-ids/' + this.checkedOrgIds.join('-'))
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.displayData();
                        this.leftSidebarService.refresh.emit('orgManagement');
                    },
                    error => {
                        this.displayData();
                    }
                );
        }
    }
    toModify() {
        if (this.orgId != null && this.orgId !== '-1') {
            if ($('.org-list:checked').length > 1) {
                alert('一次只能修改一个组织机构！');
                return;
            }
            if ($('.org-list:checked').length === 0) {
                alert('请选择需要修改的组织机构！');
                return;
            }
            const orgId = $('.org-list:checked').val();
            for (let i = 0; i < this.orgs.length; i++) {
                if (this.orgs[i].orgId === orgId) {
                    this.toModifyOrgId = orgId;
                    this.toModifyOrgName = this.orgs[i].orgName;
                    this.toModifyOrgCode = this.orgs[i].orgCode;
                    this.toModifyOrgType = this.orgs[i].orgType;
                    this.toModifyIsLocked = this.orgs[i].isLocked;
                }
            }
            $('#modifyModal').modal('show');
        } else {
            alert('只能修改自己所拥有的组织机构的子组织机构！');
        }
    }
    modify() {
        this.http
            .put('/user/back/org/' + this.toModifyOrgId, {
                orgName: this.toModifyOrgName,
                orgCode: this.toModifyOrgCode,
                orgType: this.toModifyOrgType,
                isLocked: this.toModifyIsLocked,
                parentId: this.orgId,
                orgId: this.toModifyOrgId
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#modifyModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('orgManagement');
                },
                error => {}
            );
    }
    toMove() {
        if (this.checkedOrgIds == null || this.checkedOrgIds.length === 0) {
            alert('请选择需要移动的组织机构');
            return;
        }
        $('#moveToModal').modal('show');
        // this.toMoveOrgTree = JSON.parse(localStorage.getItem('org-tree'));
        this.http
            .get('/user/back/org/tree')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.toMoveOrgTree = result.tree;
                    localStorage.setItem(
                        'org-trees',
                        JSON.stringify(this.displayOrgTree)
                    );
                },
                error => {
                    this.toMoveOrgTree = null;
                }
            );
    }
    move() {
        if (this.checkedOrgIds == null || this.checkedOrgIds.length === 0) {
            alert('请选择需要移动的组织机构');
            return;
        }
        this.moveToOrgId = $('input[name="moveToOrgId"]:checked').val();
        if (this.moveToOrgId == null) {
            alert('请选择目标组织机构！');
            return;
        }
        this.http
            .put('/user/back/org/move-to/' + this.moveToOrgId, {
                orgIds: this.checkedOrgIds
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#moveToModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('orgManagement');
                },
                error => {}
            );
    }
    displayTree() {
        $('#displayTreeModal').modal('show');
        // this.displayOrgTree = JSON.parse(localStorage.getItem('org-tree'));
        this.http
            .get('/user/back/org/tree')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.displayOrgTree = result.tree;
                    localStorage.setItem(
                        'org-trees',
                        JSON.stringify(this.displayOrgTree)
                    );
                },
                error => {
                    this.displayOrgTree = null;
                }
            );
    }
    goToNode(orgId) {
        $('#displayTreeModal').modal('hide');
        this.orgId = orgId;
        this.pageNo = 1;
        this.router.navigate([
            'org-management/' +
                this.orgId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    lock(orgId) {
        this.http
            .put('/user/back/org/' + orgId + '/lock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    unlock(orgId) {
        this.http
            .put('/user/back/org/' + orgId + '/unlock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    manageUserJobRoles(orgId, orgName) {
        $('#jobUserRolesModal').modal('show');
        this.minPageOrgId = orgId;
        this.userJobRolesOrgName = orgName;
        this.minPageNo = 1;
        this.minPageSize = parseInt(localStorage.getItem('minPageSize'), 10);
        if (this.minPageSize == null || isNaN(this.minPageSize)) {
            this.minPageSize = 10;
        }
        this.displayMinData();
    }
    setMinPageSize(pageSize) {
        this.minPageNo = 1;
        this.minPageSize = pageSize;
        localStorage.setItem('minPageSize', pageSize);
        this.displayMinData();
    }
    goToMinPage(pageNo) {
        this.minPageNo = pageNo;
        this.displayMinData();
    }
    clearMinKeywords() {
        this.minSearchKeywords = '';
    }
    displayMinData() {
        $('#minLoading').show();
        this.http
            .get(
                '/user/back/job/page/org-' +
                    this.minPageOrgId +
                    '/search-' +
                    this.minSearchKeywords +
                    '/order-by-' +
                    this.minOrderBy +
                    '/order-type-' +
                    this.minOrderType +
                    '/page-no/' +
                    this.minPageNo +
                    '/page-size/' +
                    this.minPageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    $('#minLoading').hide();
                    this.minPageNo = result.pageNo;
                    this.minPageSize = result.pageSize;
                    this.minTotal = result.total;
                    this.jobUserRoles = result.list;
                    this.minTotalPages = result.totalPages;
                    this.minOrderBy = result.orderBy;
                    this.minOrderType = result.orderType;
                },
                error => {}
            );
    }
    minSort(orderBy) {
        if (this.minOrderBy === orderBy) {
            if (this.minOrderType === 'asc') {
                this.minOrderType = 'desc';
            } else {
                this.minOrderType = 'asc';
            }
        } else {
            this.minOrderBy = orderBy;
        }
        this.displayMinData();
    }
    checkAllUserJobRoles() {
        if (this.checkedAllUserJobRoles === false) {
            this.checkedAllUserJobRoles = true;
            this.checkedUserJobRoleIds = [];
            for (let i = 0; i < this.jobUserRoles.length; i++) {
                this.checkedUserJobRoleIds.push(
                    this.jobUserRoles[i].otherResults.id
                );
            }
            $('.job-list').prop('checked', true);
        } else {
            this.checkedAllUserJobRoles = false;
            this.checkedUserJobRoleIds = [];
            $('.job-list').prop('checked', false);
        }
    }
    checkUserJobRole() {
        this.checkedUserJobRoleIds = [];
        if ($('.job-list').length === $('.job-list:checked').length) {
            this.checkedAllUserJobRoles = true;
        } else {
            this.checkedAllUserJobRoles = false;
        }
        const checkedUserJobRoleIds = this.checkedUserJobRoleIds;
        $('.job-list:checked').each(function() {
            checkedUserJobRoleIds.push($(this).val());
        });
    }
    toDeleteUserJobRoles() {
        if (this.checkedUserJobRoleIds.length <= 0) {
            alert('请先选中需要删除的职员Role！');
            return;
        }
        if (confirm('确定删除选中的职员Role吗？')) {
            this.http
                .delete(
                    '/user/back/job/by-ids/' +
                        this.checkedUserJobRoleIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.checkedAllUserJobRoles = false;
                        this.checkedUserJobRoleIds = [];
                        this.displayMinData();
                    },
                    error => {
                        this.displayMinData();
                    }
                );
        }
    }
}
